using System;
using System.Web ;

namespace Crawler
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class PathExtractor : IPathExtractor
	{
		public ICentralFactory factory;

		public PathExtractor(ICentralFactory factory)
		{
			this.factory = factory;
		}

		public string ExtractRelativePathFromUrl(IKey key)
		{
			Uri url = new Uri(key.ToString());
			string result = url.LocalPath + url.Fragment ;
			Uri domain = new Uri(this.factory.GetDomain()  );
			if(result.StartsWith(domain.LocalPath))
				result = result.Substring(domain.LocalPath.Length ); 
			else
				result = result.Substring(result.IndexOf('/')+1); 
			if(url.Scheme == "file"){
				result = result.Substring(result.IndexOf(':')+ 1);
				result = result.Replace(@"\",@"/");
			}
			return HttpUtility.UrlDecode(result) ;   
		}

		public string ExtractAbsolutePathFromUrl(IKey key)
		{
			string relativeUrl = ExtractRelativePathFromUrl(key);
			string absoluteUrl = factory.GetPath().ToString();  
			absoluteUrl = absoluteUrl.Replace(@"\",@"/");
			string result = absoluteUrl  + "/" + relativeUrl;
			result = result.Replace(@"//",@"/"); 
			return result;
		}
	}
}
